import API from '../CloudServer/send.js'
import { syncFn, syncCloneFn } from './shareSave.js'
import dayjs from 'dayjs'
import pool from '../DB/db.js'
import sqlAPI from './sqlLite.js'
import timedTaskAPI from './timedTask.js'
export function setCloudDiskTaskFn(app) {
  // 当应用退出或不再需要连接时，关闭连接池
  process.on('SIGINT', async () => {
    await pool.close()
    console.log('Connection pool closed.')
    process.exit(0)
  })
  app.post('/task/create', async (req, result) => {
    const time = dayjs().format('YYYY-MM-DD HH:mm:ss')
    const taskData = {
      ...req.body,
      create_time: time,
      update_time: time,
    }
    const keys = Object.keys(taskData).join(', ')
    const values = Object.values(taskData)
    const replace = Object.keys(taskData)
      .map(() => '?')
      .join(', ')
    // 插入数据
    const insertSql = `INSERT INTO task (${keys}) VALUES (${replace});`

    pool.run(insertSql, values, function (err) {
      if (err) {
        result.status(500).json(err)
        console.error('Insertion failed: ' + err.message)
      } else {
        result.status(200).json({ res_code: 0, res_message: '创建成功' })
        console.log(`Inserted data with rowid ${this.lastID}`)
      }
    })
  })
  app.post('/task/list', async (req, result) => {
    const { current = 1, pageSize = 10, task_name = '' } = req.body
    let whereClause = task_name ? `WHERE task_name LIKE '%${task_name}%'` : ''

    // 计算总数
    const totalCountQuery = `SELECT COUNT(*) AS total FROM task ${whereClause}`
    // 分页查询
    const offset = (current - 1) * pageSize
    const selectSql = `SELECT * FROM task ${whereClause} ORDER BY create_time DESC LIMIT ${pageSize} OFFSET ${offset}`
    pool.get(totalCountQuery, [], (err, countRow) => {
      if (err) {
        result.status(500).json(err)
      } else {
        pool.all(selectSql, [], (selectErr, rows) => {
          if (selectErr) {
            console.error('Query failed: ' + selectErr.message)
            result.status(500).json(selectErr)
          } else {
            result.status(200).json({ total: countRow.total, data: rows })
            // console.log(rows)
          }
        })
      }
    })
  })
  app.post('/user/update', async (req, result) => {
    const updateData = {
      ...req.body,
      cookies: JSON.stringify(req.cookies),
    }
    sqlAPI.InsertOrUpdateFn('users', 'login_name', updateData, result)
  })
  app.post('/user/getByloginName', async (req, result) => {
    sqlAPI.selectFn('users', 'login_name', req.body.login_name, result)
  })
  app.post('/user/get', (req, result) => {})
  app.post('/task/executeTask', async (req, result) => {
    syncCloneFn(req.body, req.cookies, result, pool)
  })
  app.post('/task/executeTaskAll', async (req, result) => {
    syncFn({ cookies: req.cookies }, result, pool)
  })
  // 更新任务数据
  app.post('/task/update', (req, result) => {
    const { id, update_time, ...updates } = req.body
    const setClause = Object.keys(updates)
      .map((key) => `${key} = ?`)
      .join(', ')
    const values = Object.values(updates)
    const updateSql = `UPDATE task SET ${setClause}, update_time = datetime('now', '+8 hours') WHERE id = ?`
    const updateValues = [...values, id]
    pool.run(updateSql, updateValues, function (err) {
      if (err) {
        console.error('Update failed: ' + err.message)
        result.status(500).json(err)
      } else {
        console.log(`Updated ${this.changes} row(s)`)
        result.status(200).json({ res_code: 0, res_message: '更新成功' })
      }
    })
  })
  // 删除任务
  app.post('/task/delete', (req, result) => {
    pool.run('DELETE FROM task WHERE id = ?', [req.body.id], function (err) {
      if (err) {
        console.error('Update failed: ' + err.message)
        result.status(500).json(err)
      } else {
        console.log(`Updated ${this.changes} row(s)`)
        result.status(200).json({ res_code: 0, res_message: '删除成功' })
      }
    })
  })
  // 获取所有任务
  app.post('/task/getAll', (req, result) => {
    sqlAPI.getAllTasks(req, result)
  })
  // 创建定时任务
  app.post('/task/timed/create', (req, result) => {
    // sqlAPI.getAllTasks(req, result)
    // console.log('req.cookies >>>', req.cookies)
    timedTaskAPI.createTimedTask(req.body.login_name, result)
  })
}
